package com.cqw.commontest.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-09-15 14:40
 * @Description: 多线程测试1
 */
public class ThreadTest1 {

    public static void main(String[] args) {
        //同步的，只会输出"听音乐"
        //listenMusic();
        //playGame();

        //匿名内部类实现异步,会输出"听音乐","打游戏"
        /*new Thread() {
            @Override
            public void run() {
                listenMusic();
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                playGame();
            }
        }.start();*/

        //采用继承Thread方式
        //new Game().start();
        //new Music().start();

        //采用实现 Runnable 的方式
//        Game1 game1 = new Game1();
//        Thread thread = new Thread(game1);
//        thread.start();
//
//        Music1 music1 = new Music1();
//        Thread thread1 = new Thread(music1);
//        thread1.start();

        //采用实现 Callable 的方式
        /**
         * 创建Callable接口的实现类 ，并实现Call方法
         * 创建Callable实现类的实现，使用FutureTask类包装Callable对象，该FutureTask对象封装了
         * Callable对象的Call方法的返回值
         * 使用FutureTask对象作为Thread对象的target创建并启动线程
         * 调用FutureTask对象的get()来获取子线程执行结束的返回值
         */
        Callable<String> shopping = new Shopping();//创建Shopping
        FutureTask<String> futureTask = new FutureTask<>(shopping);
        Thread thread2 = new Thread(futureTask);
        thread2.start();//启动线程
        String s = null;
        try {
            s = futureTask.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(s);


    }


    public static void listenMusic() {
        while (true) {
            System.out.println("听音乐");
        }
    }

    public static void playGame() {
        while (true) {
            System.out.println("打游戏");
        }
    }
}

class Game extends Thread {
    @Override
    public void run() {
        System.out.println("打游戏");
    }
}

class Music extends Thread {
    @Override
    public void run() {
        System.out.println("听音乐");
    }
}


class Game1 implements Runnable {
    @Override
    public void run() {
        System.out.println("打游戏");
    }
}

class Music1 implements Runnable {
    @Override
    public void run() {
        System.out.println("听音乐");
    }
}


class Shopping implements Callable<String> {
    @Override
    public String call() throws Exception {
        Thread.sleep(10000);
        return "购物花了1000元";
    }
}

